package com.ruoyi.project.manage.item.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.constant.ProjectConstants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.project.manage.approveLog.domain.ApproveLog;
import com.ruoyi.project.manage.approveLog.mapper.ApproveLogMapper;
import com.ruoyi.project.manage.file.domain.ProjectFile;
import com.ruoyi.project.manage.file.mapper.ProjectFileMapper;
import com.ruoyi.project.manage.item.domain.StageItem;
import com.ruoyi.project.manage.item.mapper.StageItemMapper;
import com.ruoyi.project.manage.project.domain.Project;
import com.ruoyi.project.manage.project.mapper.ProjectMapper;
import com.ruoyi.project.system.dict.mapper.DictDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.manage.item.mapper.ProjectItemMapper;
import com.ruoyi.project.manage.item.domain.ProjectItem;
import com.ruoyi.project.manage.item.service.IProjectItemService;
import com.ruoyi.common.utils.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 项目事项Service业务层处理
 * 
 * @author fangkun
 * @date 2022-04-02
 */
@Service
@Transactional
public class ProjectItemServiceImpl implements IProjectItemService 
{
    @Autowired
    private ProjectItemMapper projectItemMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ApproveLogMapper approveLogMapper;
    @Autowired
    private ProjectFileMapper projectFileMapper;
    @Autowired
    private DictDataMapper dictDataMapper;
    @Autowired
    private StageItemMapper stageItemMapper;

    /**
     * 查询项目事项
     * 
     * @param projectItemId 项目事项主键
     * @return 项目事项
     */
    @Override
    public ProjectItem selectProjectItemByProjectItemId(Long projectItemId)
    {
        return projectItemMapper.selectProjectItemByProjectItemId(projectItemId);
    }

    /**
     * 查询项目事项列表
     * 
     * @param projectItem 项目事项
     * @return 项目事项
     */
    @Override
    public List<ProjectItem> selectProjectItemList(ProjectItem projectItem)
    {
        return projectItemMapper.selectProjectItemList(projectItem);
    }

    /**
     * 新增项目事项
     * 
     * @param projectItem 项目事项
     * @return 结果
     */
    @Override
    public int insertProjectItem(ProjectItem projectItem)
    {
        projectItem.setCreateTime(DateUtils.getNowDate());
        return projectItemMapper.insertProjectItem(projectItem);
    }

    @Override
    public int manageProjectItem(ProjectItem projectItem) {

        ProjectItem oriProjectItem = projectItemMapper.selectProjectItemByProjectItemId(projectItem.getProjectItemId());

        // 审批流转记录
        ApproveLog approveLog = new ApproveLog();
        approveLog.setEntityType(ProjectConstants.APPROVAL_TYPE_ITEM);
        approveLog.setEntityId(projectItem.getProjectItemId());
        approveLog.setApproveResult(projectItem.getProjectItemStatus());
        String dictLabel = dictDataMapper.selectDictLabel("eb_project_item_status", projectItem.getProjectItemStatus() + "");
        approveLog.setRemark(dictLabel);
        // 设置流转记录
        String approveComment = "《" + oriProjectItem.getStageItem().getItemName() + "》" + dictLabel;
        approveLog.setApproveComment(approveComment);
        approveLog.setCreateTime(DateUtils.getNowDate());
        approveLog.setCreateBy("审核员:" + ShiroUtils.getSysUser().getUserName());
        approveLog.setUpdateTime(DateUtils.getNowDate());
        approveLog.setUpdateBy(ShiroUtils.getSysUser().getUserName());
        approveLogMapper.insertApproveLog(approveLog);

        // 处理文件数据
        List<ProjectFile> fileList = projectItem.getFileList();
        if (fileList != null && fileList.size() > 0) {
            // 删除之前对应的文件信息
            projectFileMapper.deleteProjectFileByProjectItemId(oriProjectItem.getProjectItemId());

            for (ProjectFile projectFile : fileList) {
                projectFile.setProjectId(oriProjectItem.getProjectId());
                projectFile.setProjectFileType((int) ProjectConstants.APPROVAL_TYPE_PROJECT);
                projectFile.setProjectItemId(oriProjectItem.getProjectItemId());
                projectFile.setApproveLogId(approveLog.getApproveLogId());
                projectFile.setStatus(UserConstants.NORMAL);
                projectFile.setCreateTime(DateUtils.getNowDate());
                projectFile.setCreateBy(ShiroUtils.getLoginName());
                projectFile.setUpdateTime(DateUtils.getNowDate());
                projectFile.setUpdateBy(ShiroUtils.getLoginName());

                projectFileMapper.insertProjectFile(projectFile);
            }
        }

        // 处理项目信息
        Project oriProject = projectMapper.selectProjectByProjectId(oriProjectItem.getProjectId());
        Project project = new Project();
        project.setProjectId(oriProjectItem.getProjectId());
        project.setUpdateTime(DateUtils.getNowDate());
        project.setUpdateBy(ShiroUtils.getLoginName());

        // 获取项目事项阶段信息
        StageItem stageItem = stageItemMapper.selectStageItemByStageItemId(oriProjectItem.getItemId());
        // 立项阶段上传立项批复文件后，自动进入审批阶段
        if (ProjectConstants.PROJECT_INIT == stageItem.getStageId().intValue() && projectItem.getProjectItemStatus() == ProjectConstants.ITEM_DONE) {
            project.setProjectStage(ProjectConstants.PROJECT_APPROVAL);
        }
        // 上传施工许可证，项目则进入施工阶段（代表项目开工）
        if (stageItem.getItemName().equals("施工许可证") && projectItem.getProjectItemStatus() == ProjectConstants.ITEM_DONE) {
            project.setProjectStage(ProjectConstants.PROJECT_IMPLEMENT);

            // 三个一批逻辑
            // 就是项目标签是三个一批项目，代表项目开工
            if (StringUtils.isNotBlank(oriProject.getProjectLabel()) && oriProject.getProjectLabel().contains(ProjectConstants.LABEL_THREE_ONE + "")) {
                project.setProjectProgress(ProjectConstants.PROCESS_IMPLEMENT);
            }
        }

        // 如上传了验收报告，则项目进入验收阶段（代表项目结束或投产）
        if (stageItem.getItemName().equals("验收报告") && projectItem.getProjectItemStatus() == ProjectConstants.ITEM_DONE) {
            project.setProjectStage(ProjectConstants.PROJECT_INSPECTED);

            // 三个一批逻辑
            // 就是项目标签是三个一批项目，代表项目结束或投产
            if (StringUtils.isNotBlank(oriProject.getProjectLabel()) && oriProject.getProjectLabel().contains(ProjectConstants.LABEL_THREE_ONE + "")) {
                project.setProjectProgress(ProjectConstants.PROCESS_COMPLETED);
            }
        }

        // 判断项目阶段和项目进度不可回滚
        if (project.getProjectStage() != null && oriProject.getProjectStage() != null && oriProject.getProjectStage() > project.getProjectStage()) {
            project.setProjectStage(oriProject.getProjectStage());
        }
        if (project.getProjectProgress() != null && oriProject.getProjectProgress() != null && oriProject.getProjectProgress() > project.getProjectProgress()) {
            project.setProjectProgress(oriProject.getProjectProgress());
        }


        projectMapper.updateProject(project);
        // 处理项目事项信息
        projectItem.setUpdateTime(DateUtils.getNowDate());
        projectItem.setUpdateBy(ShiroUtils.getLoginName());
        return projectItemMapper.updateProjectItem(projectItem);
    }

    /**
     * 修改项目事项
     * 
     * @param projectItem 项目事项
     * @return 结果
     */
    @Override
    public int updateProjectItem(ProjectItem projectItem)
    {
        // 添加新的项目事项
        String itemIds = projectItem.getItemIds();

        if (itemIds == null || itemIds.length() == 0) {
            // 删除之前项目的事项内容
            projectItemMapper.deleteProjectItemByProjectId(projectItem.getProjectId());
            itemIds = "";
        }
        String[] itemIdArray = itemIds.split(",");
        // 获取项目所有的关联事项
        ProjectItem projectQuery = new ProjectItem();
        projectQuery.setProjectId(projectItem.getProjectId());
        List<ProjectItem> projectItems = projectItemMapper.selectProjectItemList(projectQuery);

        if (StringUtils.isNotEmpty(itemIds)) {

            for (int i = 0; i < itemIdArray.length; i++) {
                int finalI = i;
                List<ProjectItem> collect = projectItems.stream().filter(item -> item.getItemId().intValue() == Long.valueOf(itemIdArray[finalI])).collect(Collectors.toList());

                if (collect == null || collect.size() == 0) {
                    StageItem stageItem = stageItemMapper.selectStageItemByStageItemId(Long.valueOf(itemIdArray[finalI]));
                    //不存在的插入
                    ProjectItem param = new ProjectItem();
                    param.setProjectId(projectItem.getProjectId());
                    param.setItemId(Long.valueOf(itemIdArray[i]));
                    param.setProjectItemStatus(ProjectConstants.ITEM_UNSUBMIT);
                    param.setIsClose(stageItem.getIsClose());

                    param.setStatus(UserConstants.NORMAL);
                    param.setCreateTime(DateUtils.getNowDate());
                    param.setCreateBy(ShiroUtils.getLoginName());
                    param.setUpdateTime(DateUtils.getNowDate());
                    param.setUpdateBy(ShiroUtils.getLoginName());

                    projectItemMapper.insertProjectItem(param);
                }

            }

            String finalItemIds = "," + itemIds + ",";
            String delIds = projectItems.stream().filter(item -> !finalItemIds.contains("," + item.getItemId() + ",")).map(item -> item.getItemId() + "").collect(Collectors.joining(","));
            projectItemMapper.deleteProjectItemByProjectItemIds(delIds.split(","));
        }

        // 更新项目事项数据
        Project project = new Project();
        project.setProjectId(projectItem.getProjectId());
        if (StringUtils.isNotEmpty(itemIds)) {
            project.setProjectItemNum(itemIdArray.length);
        } else {
            project.setProjectItemNum(0);
        }

        project.setUpdateTime(DateUtils.getNowDate());
        project.setUpdateBy(ShiroUtils.getLoginName());

        projectMapper.updateProject(project);

        return itemIdArray.length;
    }

    /**
     * 批量删除项目事项
     * 
     * @param projectItemIds 需要删除的项目事项主键
     * @return 结果
     */
    @Override
    public int deleteProjectItemByProjectItemIds(String projectItemIds)
    {
        return projectItemMapper.deleteProjectItemByProjectItemIds(Convert.toStrArray(projectItemIds));
    }

    /**
     * 删除项目事项信息
     * 
     * @param projectItemId 项目事项主键
     * @return 结果
     */
    @Override
    public int deleteProjectItemByProjectItemId(Long projectItemId)
    {
        return projectItemMapper.deleteProjectItemByProjectItemId(projectItemId);
    }

    @Override
    public int changeClose(ProjectItem projectItem) {
        // 处理项目事项信息
        projectItem.setUpdateTime(DateUtils.getNowDate());
        projectItem.setUpdateBy(ShiroUtils.getLoginName());
        return projectItemMapper.updateProjectItem(projectItem);
    }
}
